package com.tianyi.productInfo;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tianyi.brand.BrandService;
import com.tianyi.classify.ClassifyService;
import com.tianyi.dao.entity.brand.Brand;
import com.tianyi.dao.entity.classify.Classify;
import com.tianyi.dao.entity.orders.Orders;
import com.tianyi.dao.entity.productInfo.ProductInfo;
import com.tianyi.dao.entity.productInfo.ProductInfoExample;
import com.tianyi.dao.entity.productPhoto.ProductPhoto;
import com.tianyi.dao.mapper.ProductInfoMapper;
import com.tianyi.fileUpload.FileUploadService;
import com.tianyi.lib.model.WebResult;
import com.tianyi.lib.req.ProductReq;
import com.tianyi.lib.req.QueryPage;
import com.tianyi.lib.result.ColorPriceInventory;
import com.tianyi.lib.result.ProductIdNoName;
import com.tianyi.lib.result.ProductInfoOrderResult;
import com.tianyi.sysUser.SysUserService;
import com.tianyi.url.UrlService;
import com.tianyi.vo.product.ProductDetailVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.*;


/**
 *
 * @author cuixuhui
 * @date 2020/06/18
 */
@Service
public class ProductService {

    private static final Logger logger = LoggerFactory.getLogger(ProductService.class);

    @Autowired
    private ProductBaseService productBaseService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private ClassifyService classifyService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private UrlService urlService;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private ProductInfoMapper productInfoMapper;


    private WebResult<String> preCheck(ProductReq req){

        if (StringUtils.isBlank(req.getProductNo())){
            return WebResult.error("货号不能为空");
        }

        if (productInfoMapper.selectByProductNumber(req.getProductName()) != null){
            return WebResult.error("货号不能为重复");
        }

        if (StringUtils.isBlank(req.getProductName())){
            return WebResult.error("商品名不能为空");
        }
        if (Objects.isNull(req.getBrandId())){
            return WebResult.error("品牌不能为空");
        }
        Brand brand = brandService.queryBrandByBrandId(req.getBrandId());
        if (Objects.isNull(brand)){
            return WebResult.error("品牌不不存在");
        }

        if (StringUtils.isBlank(req.getPhotoPath())){
            return WebResult.error("图片不能为空");
        }
        if (StringUtils.isBlank(req.getAnnual())){
            return WebResult.error("年度不能为空");
        }
        if (StringUtils.isBlank(req.getQuarter())){
            return WebResult.error("季度不能为空");
        }
        if (Objects.isNull(req.getStatus())){
            req.setStatus(Boolean.TRUE);
        }
        long now = System.currentTimeMillis();
        if (Objects.isNull(req.getOpenStart())){
            req.setOpenStart(new Date(now));
        }
        if (Objects.isNull(req.getOpenEnd())){
            req.setOpenEnd(new Date(now + 24*60*60*1000));
        }
        if (req.getOpenEnd().before(req.getOpenStart())){
            return WebResult.error("开放时间结束时间不能早于开始时间");
        }
//        if (Objects.isNull(req.getClassifyId())){
//            return WebResult.error("分类不能为空");
//        }
//        Classify classify = classifyService.queryClassifyByClassifyId(req.getClassifyId());
//        if (Objects.isNull(classify)){
//            return WebResult.error("分类不存在");
//        }
        List<ProductInfo> productInfos = productBaseService.queryProductInfoByProductNoName(req.getProductNo(), req.getProductName());
        if (CollectionUtils.isEmpty(productInfos)){
            return WebResult.ok("success");
        }
        ProductInfo productInfo = productInfos.get(0);
        if (Objects.equals(req.getId(), productInfo.getId())){
            return WebResult.ok("success");
        }
        return WebResult.error("商品已存在");
    }

    public WebResult<List<ProductIdNoName>> queryProductInfoAllIdNoName(){
        List<ProductInfo> result = productInfoMapper.selectByExample(new ProductInfoExample());
        List<ProductIdNoName> resultSimple = new ArrayList<>();
        for(ProductInfo productInfo : result){
            ProductIdNoName productInfoTemp = new ProductIdNoName();
            productInfoTemp.setId(productInfo.getId());
            productInfoTemp.setProductNo(productInfo.getProductNo());
            productInfoTemp.setProductName(productInfo.getProductName());
            resultSimple.add(productInfoTemp);
        }
        return WebResult.ok(resultSimple);
    }

    public WebResult<String> addProductInfo(ProductReq req) {

        WebResult<String> preCheck = preCheck(req);
        if (!preCheck.isSuccess()) {
            return preCheck;
        }

        ProductInfo baseProductInfo = productBaseService.gentInsertProductByReq(req);
        baseProductInfo = productBaseService.insertProductInfo(baseProductInfo);

        if (Objects.isNull(baseProductInfo)) {
            productBaseService.deleteProductInfoById(baseProductInfo.getId());
            return WebResult.error("保存失败，请联系管理员");
        }

        ProductPhoto productPhoto = productBaseService.gentBaseProductPhotoByReq(baseProductInfo.getId(), req);
        productPhoto = productBaseService.insertProductPhoto(productPhoto);

        if (Objects.isNull(productPhoto)) {

            productBaseService.deleteProductInfoById(baseProductInfo.getId());
            productBaseService.deleteProductPhotoByProductId(baseProductInfo.getId());
            return WebResult.error("保存失败，请联系管理员");
        }
        return WebResult.ok("success");
    }

    public WebResult<String> addProductInfoNew(ProductInfoOrderResult req) {

        if (productInfoMapper.selectByProductNumber(req.getProductNo()).size() != 0){
            return WebResult.error("货号不能为重复");
        }
        if(req.getCargoList() == null){
            return WebResult.error("有关键信息为空，无法保存");
        }
        for(ColorPriceInventory colorPriceInventory : req.getCargoList()){
            ProductInfo productInfoTemp = new ProductInfo();
            productInfoTemp.setProductNo(req.getProductNo());
            productInfoTemp.setProductName(req.getProductName());
            productInfoTemp.setBrandId(req.getBrandId());
            productInfoTemp.setClassifyId(req.getClassifyId());
            productInfoTemp.setOperator(req.getOperator());
            productInfoTemp.setSize(colorPriceInventory.getSize());
            productInfoTemp.setPrice(new BigDecimal(colorPriceInventory.getPrice()));
            productInfoTemp.setColour(colorPriceInventory.getColor());
            productInfoTemp.setInventory((int)(colorPriceInventory.getInventory()));
            Calendar calendar = Calendar.getInstance();
            productInfoTemp.setGmtCreate(calendar.getTime());
            productInfoMapper.insert(productInfoTemp);
        }

        return WebResult.ok("success");
    }

    //留给GRD的JSON接口，忽略掉cargolist
    public WebResult<String> addProductInfoNewJson(ProductInfoOrderResult req) {

        if (productInfoMapper.selectByProductNumber(req.getProductNo()).size() != 0){
            return WebResult.error("货号不能为重复");
        }

            ProductInfo productInfoTemp = new ProductInfo();
            productInfoTemp.setProductNo(req.getProductNo());
            productInfoTemp.setProductName(req.getProductName());
            productInfoTemp.setBrandId(req.getBrandId());
            productInfoTemp.setClassifyId(req.getClassifyId());
            productInfoTemp.setOperator(req.getOperator());
            productInfoTemp.setExt1(req.getExt1());//json from GRD
            Calendar calendar = Calendar.getInstance();
            productInfoTemp.setGmtCreate(calendar.getTime());
            productInfoTemp.setGmtModified(calendar.getTime());
            productInfoTemp.setOpenStart(req.getOpenStart());
            productInfoTemp.setOpenEnd(req.getOpenEnd());
            productInfoTemp.setAnnual(req.getAnnual());
            productInfoTemp.setQuarter(req.getQuarter());
            productInfoTemp.setPrice(new BigDecimal(req.getPrice()));
            if(req.getInventory() != null){
                productInfoTemp.setInventory((req.getInventory()).intValue());
            }
            productInfoTemp.setStatus(req.getStatus());
            productInfoMapper.insert(productInfoTemp);

        return WebResult.ok("success");
    }

    public WebResult<String> updateProductInfoNewJsonById(ProductInfoOrderResult req){
        ProductInfo productInfoTemp = new ProductInfo();
        productInfoTemp.setProductNo(req.getProductNo());
        productInfoTemp.setProductName(req.getProductName());
        productInfoTemp.setBrandId(req.getBrandId());
        productInfoTemp.setClassifyId(req.getClassifyId());
        productInfoTemp.setOperator(req.getOperator());
        productInfoTemp.setExt1(req.getExt1());//json from GRD
        Calendar calendar = Calendar.getInstance();
        productInfoTemp.setGmtModified(calendar.getTime());
        productInfoTemp.setOpenStart(req.getOpenStart());
        productInfoTemp.setOpenEnd(req.getOpenEnd());
        productInfoTemp.setAnnual(req.getAnnual());
        productInfoTemp.setQuarter(req.getQuarter());
        productInfoTemp.setPrice(new BigDecimal(req.getPrice()));
        productInfoTemp.setInventory((req.getInventory()).intValue());
        productInfoTemp.setStatus(req.getStatus());
        productInfoMapper.updateByPrimaryKey(productInfoTemp);

        return WebResult.ok("success");
    }

    public WebResult<String> deleteProductInfoNewJsonById(long id){

        productInfoMapper.deleteByPrimaryKey(id);

        return WebResult.ok("success");
    }

    /**
     * 分页接口
     * @param req
     * @return
     */
    /*
    public WebResult<PageInfo<ProductVO>> queryProductInfoPage(ProductReq req) {

        PageInfo<ProductInfo> pageInfo = productBaseService.queryProductInfoPage(req);

        PageInfo<ProductVO> voPageInfo = new PageInfo<>();
        BeanUtils.copyProperties(pageInfo, voPageInfo);

        List<ProductInfo> pageInfoList = pageInfo.getList();
        if (CollectionUtils.isEmpty(pageInfoList)){
            return WebResult.ok(voPageInfo);
        }

        List<Long> brandIds = pageInfoList.stream().map(ProductInfo::getBrandId).distinct().collect(Collectors.toList());
        Map<Long, String> brandIdNameMap = brandService.queryBrandNameMapByBrandIds(brandIds);

        List<Long> classifyIds = pageInfoList.stream().map(ProductInfo::getClassifyId).distinct().collect(Collectors.toList());
        Map<Long, String> classifyIdNameMap = classifyService.queryClassifyNameMapByBrandIds(classifyIds);

        List<Long> empIds = pageInfoList.stream().map(ProductInfo::getOperator).distinct().collect(Collectors.toList());
        Map<Long, String> sysUserNameMap = sysUserService.queryUserNameMapByUserIds(empIds);

        List<ProductVO> productVOS = pageInfoList.stream().map(ret -> {
            ProductVO vo = new ProductVO();
            BeanUtils.copyProperties(ret, vo);

            String brandNameMap = brandIdNameMap.get(ret.getBrandId());
            String brandName = StringUtils.isNotBlank(brandNameMap) ? brandNameMap : ret.getBrandId() + "";
            vo.setBrandName(brandName);

            String classifyNameMap = classifyIdNameMap.get(ret.getClassifyId());
            String classifyName = StringUtils.isNotBlank(classifyNameMap) ? classifyNameMap : ret.getClassifyId() + "";
            vo.setClassifyName(classifyName);

            String operatorNameMap = sysUserNameMap.get(ret.getOperator());
            String operatorName = StringUtils.isNotBlank(operatorNameMap) ? operatorNameMap : ret.getOperator()+ "";
            vo.setOperatorName(operatorName);
            return vo;
        }).collect(Collectors.toList());

        voPageInfo.setList(productVOS);
        return WebResult.ok(voPageInfo);
    }
     */

    public WebResult<PageInfo<ProductInfo>> queryProductInfoByPageJSON(QueryPage queryPage){
        //ProductInfoExample example = new ProductInfoExample();
        //Page<ProductInfo> productInfos = productInfoMapper.selectByExample(example, new RowBounds(req.getPageNo(), req.getPageSize()));
        //PageInfo<ProductInfo> pageInfos = productInfos.toPageInfo();
        //return WebResult.ok(pageInfos);

        ProductInfo productInfo = new ProductInfo();
        List<ProductInfo> result0 = productInfoMapper.selectAll();
        System.out.println(result0.get(0).toString());
        if(result0.size()==0){
            return WebResult.error("数据库相应内容为空！");
        }
        Page<ProductInfo> productInfoPage = productInfoMapper.selectByPage((queryPage.getPageNo()-1)*queryPage.getPageSize(),
                queryPage.getPageSize());
        productInfoPage.setPageNum(queryPage.getPageNo());
        productInfoPage.setPageSize(queryPage.getPageSize());
        int pagesCount;
        if (result0.size()%queryPage.getPageSize() == 0){
            pagesCount = result0.size()/queryPage.getPageSize();
        }else {
            pagesCount = result0.size()/queryPage.getPageSize() +1;
        }
        if(pagesCount!=0&&(queryPage.getPageNo()<1||queryPage.getPageNo()>pagesCount)){
            return WebResult.error("超出分页查询范围");
        }
        boolean prevPage = false;
        boolean nextPage = false;
        if (queryPage.getPageNo()>1){
            prevPage = true;
        }
        if (queryPage.getPageNo()<pagesCount){
            nextPage = true;
        }

        productInfoPage.setPages(pagesCount);
        productInfoPage.setCount(true);
        productInfoPage.setOrderBy("id ASC");
        productInfoPage.setStartRow((queryPage.getPageNo()-1)*queryPage.getPageSize());
        productInfoPage.setEndRow((queryPage.getPageNo()-1)*queryPage.getPageSize()+queryPage.getPageSize());
        //System.out.println("Page<Orders>： "+ordersPage.toString());
        PageInfo<ProductInfo> productInfoPageInfo = productInfoPage.toPageInfo();
        productInfoPageInfo.setHasPreviousPage(prevPage);
        productInfoPageInfo.setHasNextPage(nextPage);
        productInfoPageInfo.setTotal(result0.size());
        //System.out.println("PageInfo<Orders>： "+ordersPageInfo.toString());

        return WebResult.ok(productInfoPageInfo);
    }

    /**
     * 根据商品货号获取产品信息详情
     * @param productNo
     * @return
     */
    public WebResult<List<ProductInfo>> queryProductInfoByProductNo(String productNo) {
        List<ProductInfo> productInfos = productInfoMapper.selectByProductNumber(productNo);
        if(productInfos.size()>0){
            return WebResult.ok(productInfos);
        }else{
            return WebResult.error("error to find productInfo by productName");
        }
    }

    /**
     * 获取产品信息详情
     * @param req
     * @return
     */
    public WebResult<ProductDetailVO> queryProductInfoDetail(ProductReq req) {

        if (Objects.isNull(req.getId())){
            return WebResult.error("id 不能为空");
        }
        ProductInfo productInfo = productBaseService.queryProductInfoById(req.getId());
        if (Objects.isNull(productInfo)){
            return WebResult.error("产品不存在");
        }

        Map<Long, String> brandIdNameMap = brandService.queryBrandNameMapByBrandIds(Arrays.asList(productInfo.getBrandId()));
        Map<Long, String> classifyIdNameMap = classifyService.queryClassifyNameMapByBrandIds(Arrays.asList(productInfo.getClassifyId()));
        Map<Long, String> sysUserNameMap = sysUserService.queryUserNameMapByUserIds(Arrays.asList(productInfo.getOperator()));

        ProductDetailVO vo = new ProductDetailVO();
        BeanUtils.copyProperties(productInfo, vo);

        vo.setBrandName(brandIdNameMap.get(productInfo.getBrandId()));
        vo.setClassifyName(classifyIdNameMap.get(productInfo.getClassifyId()));
        vo.setOperatorName(sysUserNameMap.get(productInfo.getOperator()));

        Long productInfoId = productInfo.getId();
        List<ProductPhoto> productPhotos = productBaseService.queryProductPhotoByProductIds(Arrays.asList(productInfoId));
        //先认为有且仅有一个
        if (CollectionUtils.isNotEmpty(productPhotos)){
            vo.setPhotoPath(productPhotos.get(0).getPhotoPath());
        }

        return WebResult.ok(vo);
    }

    public WebResult<String> deleteProductInfoById(ProductReq req) {
        Long productId = req.getId();
        if (Objects.isNull(productId)){
            return WebResult.error("productId 为空");
        }
        ProductInfo productInfo = productBaseService.queryProductInfoById(productId);
        if (Objects.isNull(productInfo)){
            return WebResult.error("产品不存在");
        }

        productBaseService.deleteProductInfoById(productId);
        productBaseService.deleteProductPhotoByProductId(productId);
        return WebResult.ok("success");
    }

    public WebResult<String> deleteProductInfoByProductNo(@RequestBody String reqNumber) {
        if(reqNumber!=null && reqNumber.length()>0) {
            productInfoMapper.deleteByProductNo(reqNumber);
            return WebResult.ok("success");
        }else{
            return WebResult.error("INVALID PARAM");
        }
    }

    public WebResult<String> updateProductInfoNew(ProductInfoOrderResult req) {
        deleteProductInfoByProductNo(req.getProductNo());
        for(ColorPriceInventory colorPriceInventory : req.getCargoList()){
            ProductInfo productInfoTemp = new ProductInfo();
            productInfoTemp.setProductNo(req.getProductNo());
            productInfoTemp.setProductName(req.getProductName());
            productInfoTemp.setBrandId(req.getBrandId());
            productInfoTemp.setClassifyId(req.getClassifyId());
            productInfoTemp.setOperator(req.getOperator());
            productInfoTemp.setSize(colorPriceInventory.getSize());
            productInfoTemp.setPrice(new BigDecimal(colorPriceInventory.getPrice()));
            productInfoTemp.setColour(colorPriceInventory.getColor());
            productInfoTemp.setInventory((int)(colorPriceInventory.getInventory()));
            Calendar calendar = Calendar.getInstance();
            productInfoTemp.setGmtModified(calendar.getTime());
            productInfoMapper.insert(productInfoTemp);
        }
        return WebResult.ok("success");
    }


    public WebResult<String> updateProductInfo(ProductReq req) {

        Long productId = req.getId();
        if (Objects.isNull(productId)){
            return WebResult.error("产品id不存在");
        }
        WebResult<String> preCheck = preCheck(req);
        if (!preCheck.isSuccess()){

            return preCheck;
        }

        ProductInfo productInfo = productBaseService.queryProductInfoById(productId);
        if (Objects.isNull(productInfo)){
            return WebResult.error("产品不存在");
        }
        productInfo.setGmtModified(new Date());

        productInfo.setProductName(req.getProductName());
        productInfo.setBrandId(req.getBrandId());
        productInfo.setClassifyId(req.getClassifyId());
        productInfo.setPrice(req.getPrice());
        productInfo.setColour(req.getColour());
        productInfo.setInventory(req.getInventory());

        //
        productInfo.setStatus(req.getStatus().toString());
        productInfo.setSize(req.getSize());
        productInfo.setAnnual(req.getAnnual());
        productInfo.setQuarter(req.getQuarter());
        productInfo.setOpenStart(req.getOpenStart());
        productInfo.setOpenEnd(req.getOpenEnd());

        Integer update = productBaseService.updateProductInfoWithVersion(productInfo);
        if (update == 0){
            return WebResult.error("修改产品信息失败，请稍后再试");
        }
        //为空，认为是不修改
        if (StringUtils.isBlank(req.getPhotoPath())){
            return WebResult.ok("success");
        }

        List<ProductPhoto> productPhotos = productBaseService.queryProductPhotoByProductIds(Arrays.asList(productId));
        if (CollectionUtils.isEmpty(productPhotos)){
            ProductPhoto productPhoto = productBaseService.gentBaseProductPhotoByReq(productId, req);
            productPhoto = productBaseService.insertProductPhoto(productPhoto);
            if (Objects.isNull(productPhoto)){
                productBaseService.deleteProductInfoById(productId);
                return WebResult.error("保存商品图片失败,请联系管理员");
            }
            return WebResult.ok("success");
        }

        //认为有且只有一个
        ProductPhoto productPhoto = productPhotos.get(0);

        if (!StringUtils.equals(req.getPhotoPath(), productPhoto.getPhotoPath())){
            fileUploadService.deletePhotoWithThumbnails(productPhoto.getPhotoPath());
        }
        productPhoto.setGmtModified(new Date());
        productPhoto.setPhotoPath(req.getPhotoPath());

        productBaseService.updateProductPhoto(productPhoto);

        return WebResult.ok("success");
    }
}
